package util

import (
	"fmt"
	"syscall"
	"time"
	"unsafe"
)

var (
	user32 = syscall.NewLazyDLL("user32.dll")
	// 定义Windows API函数
	getForegroundWindow = user32.NewProc("GetForegroundWindow")
	getWindowText       = user32.NewProc("GetWindowTextW")
	enumWindows         = user32.NewProc("EnumWindows")
	setForegroundWindow = user32.NewProc("SetForegroundWindow")
)

const (
	MAX_TITLE_LENGTH = 255
)

func getActiveWindowTitle() string {
	hwnd, _, _ := getForegroundWindow.Call()
	if hwnd == 0 {
		return "无前台窗口"
	}

	buffer := make([]uint16, MAX_TITLE_LENGTH)
	ret, _, _ := getWindowText.Call(uintptr(hwnd), uintptr(unsafe.Pointer(&buffer[0])), uintptr(MAX_TITLE_LENGTH))
	return syscall.UTF16ToString(buffer[:ret])
}

func findWindowByTitle(title string) uintptr {
	var targetHwnd uintptr
	enumWindows.Call(syscall.NewCallback(func(hwnd uintptr, lParam uintptr) uintptr {
		// 获取窗口标题
		buffer := make([]uint16, MAX_TITLE_LENGTH)
		ret, _, _ := getWindowText.Call(hwnd, uintptr(unsafe.Pointer(&buffer[0])), uintptr(MAX_TITLE_LENGTH))
		windowTitle := syscall.UTF16ToString(buffer[:ret])

		// 如果标题匹配，则返回该窗口句柄
		if windowTitle == title {
			targetHwnd = hwnd
			return 0 // 找到窗口后停止枚举
		}
		return 1 // 继续枚举
	}), 0)
	return targetHwnd
}

func setWindowForeground(hwnd uintptr) {
	// 将目标窗口设为前台窗口
	setForegroundWindow.Call(hwnd)
}

func WindowCheck() {
	// 目标窗口标题
	targetTitle := "网上股票交易系统5.0"
	// 获取当前前台窗口的标题
	activeWindowTitle := getActiveWindowTitle()
	// fmt.Println("当前窗口标题:", activeWindowTitle)

	// // 如果当前窗口标题不是目标窗口，切换到目标窗口
	if activeWindowTitle != targetTitle && activeWindowTitle != "" {
		// 查找目标窗口的句柄
		targetHwnd := findWindowByTitle(targetTitle)
		if targetHwnd != 0 {
			// 找到目标窗口，切换到该窗口
			fmt.Println("切换到目标窗口:", targetTitle)
			setWindowForeground(targetHwnd)
		} else {
			// 如果没有找到目标窗口
			fmt.Println("未找到目标窗口:", targetTitle)
		}
	}
}

func WindowCheckC() {
	// 每秒钟检测一次当前前台窗口
	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()

	// 目标窗口标题
	targetTitle := "网上股票交易系统5.0"

	for {
		select {
		case <-ticker.C:
			// 获取当前前台窗口的标题
			activeWindowTitle := getActiveWindowTitle()
			fmt.Println("当前窗口标题:", activeWindowTitle)

			// // 如果当前窗口标题不是目标窗口，切换到目标窗口
			if activeWindowTitle != targetTitle {
				// 查找目标窗口的句柄
				targetHwnd := findWindowByTitle(targetTitle)
				if targetHwnd != 0 {
					// 找到目标窗口，切换到该窗口
					fmt.Println("切换到目标窗口:", targetTitle)
					setWindowForeground(targetHwnd)
				} else {
					// 如果没有找到目标窗口
					fmt.Println("未找到目标窗口:", targetTitle)
				}
			}
		}
	}
}
